package com.liujun.spring4.demo.aop.aopproblem.solve;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author liujun
 * @version 0.0.1
 * @date 2018/09/30
 */
@Component
public class BeanSelfProxyAwareMounter implements SystemBootAddon, ApplicationContextAware {

  private Logger logger = LoggerFactory.getLogger(this.getClass());

  private ApplicationContext applicationContext;

  /**
   * 注入容器对象信息
   *
   * @param applicationContext
   * @throws BeansException
   */
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;
  }

  /** 系统启动器接口中的装配就绪方法 */
  @Override
  public void onReady() {

    Map<String, BeanSelfProxyAware> proxyAwareMap =
        applicationContext.getBeansOfType(BeanSelfProxyAware.class);

    if (null != proxyAwareMap) {
      for (BeanSelfProxyAware value : proxyAwareMap.values()) {
        value.setSelfProxy(value);

        if (logger.isDebugEnabled()) {
          logger.debug("{} 注册自身被代理的实例");
        }
      }
    }
  }

  /**
   * 值越小优先被加载处理，值越大最被被加载处理
   *
   * @return
   */
  @Override
  public int getOrder() {
    return Ordered.HIGHEST_PRECEDENCE;
  }
}
